import com.sun.deploy.uitoolkit.impl.fx.ui.FXMessageDialog;

import java.awt.*;
import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

/**
 * Created by ospip on 2017/10/2.
 * Copyright (c) 2017 LLAP. All rights reserved.
 */
public class RMB extends JFrame{
    private JTextField text_money, text_str;

    public RMB() {
        super("RMB");
        this.setBounds(300, 240, 360, 90);
        //this.setResizable(false);
        this.setBackground(Color.lightGray);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setLayout(new FlowLayout(FlowLayout.RIGHT));
        this.add(new JLabel("金额"));
        text_money = new JTextField("12345678.90", 22);
        this.add(text_money);
        text_money.addCaretListener((e) -> {
            try {
                double x = Double.parseDouble(text_money.getText());
                text_str.setText(RMB.toString(x));
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "Cannot convert String to Double");
            }
        });
        this.add(new JLabel("中文大写"));
        text_str = new JTextField(22);
        text_str.setHorizontalAlignment(JTextField.RIGHT);
        text_str.setEditable(false);
        this.add(text_str);
        this.setVisible (true);

    }
    public static String toString(double x) {
        String num = "零壹贰叁肆伍陆柒捌玖";
        String d = "分角元拾佰仟万拾佰仟亿拾佰仟兆拾佰仟";
        String ret = "";
        long p = (long)(x * 100);
        for (int c = 0; p > 0; p /= 10, ++c) {
            if (p % 10 > 0 || c == 2 || ((c - 2) % 4 == 0 && p % 1000 > 0)) ret = d.charAt(c) + ret;
            if (!(c == 0 && p % 10 == 0)) ret = num.charAt((int)(p % 10)) + ret;
            if (c == 0 && p % 100 == 0) { c = 2; ret = "元整"; }
        }
        while (ret.contains("零零")) ret = ret.replace("零零", "零");
        ret = ret.replace("零亿", "亿").replace("零万", "万").replace("零仟", "仟").
                replace("零佰", "佰").replace("零拾", "拾").replace("零元", "元");
        if (x == 0) ret = "零元" + ret;
        return ret;
    }

    public static void main(String[] args) {
        new RMB();

    }
}
